﻿using UnityEngine;
using System.Collections;
namespace GameUnit
{
    public class HPBarUWidget : UWidget
    {
        GameObject HPBarG;
        UISprite HPBarValue;
        UISprite ShiledBarValue;
        public override void Init(Unit unit)
        {
          GameObject HPBarG =  (GameObject)GameObject.Instantiate( Resources.Load("Prefab/UWidget/HPBar"));
          HPBarG.transform.parent = transform;
          this.HPBarValue = HPBarG.transform.Find("BG/HP").GetComponent<UISprite>();
          this.ShiledBarValue = HPBarG.transform.Find("BG/Shield").GetComponent<UISprite>();
          base.Init(unit);
          
        }

        public override void OnLoad()
        {
            this.Unit.AddEventHandler("hp-change", this.OnHPChange);
            this.Unit.AddEventHandler("shiled-change",this.OnShiledChange);

        }

        public void OnHPChange(string eventName,string suMsg)
        {
            this.HPBarValue.fillAmount =  (float)this.Unit.HP / (float)this.Unit.MaxHP;
        }

        public void OnShiledChange(string eventName,string suMsg)
        {
            if (this.Unit.Shiled == 0)
            {
                this.ShiledBarValue.fillAmount = 0;
                this.ShiledBarValue.transform.localPosition.Set(-66,0,0);
            }
            else
            {
                this.ShiledBarValue.transform.localPosition = new Vector3(-66 + ( this.HPBarValue.width * this.HPBarValue.fillAmount), 0,0) ;
                this.ShiledBarValue.fillAmount = ((float)this.Unit.Shiled / (float)this.Unit.MaxHP);
            }
        }
    }
}
